import React, { useEffect, useState, useRef } from "react";
// import "./SupportContestant.css";
import style from "./SupportContestant.module.css";
import instance from "../../utils/https";
import { Toast, Badge } from "react-vant";
import { v4 as uuidv4 } from "uuid"; // 导入 UUID
import flower from "./3.png";
import flower1 from "./4.png";
// 定义组件 Props 类型

interface SupportContestantProps {
  cid: any;
  onClose: (isOpen2: boolean) => void;
}
const SupportContestant : React.FC<SupportContestantProps>=({
  cid, onClose
}) => {
  // const [isOpen, onClick] = useState(false);
  const [flowerCount, setFlowerCount] = useState(0); // 第一朵鲜花的数量
  const [flowerCount2, setFlowerCount2] = useState(0); // 第二朵鲜花的数量
  const [totalPrice, setTotalPrice] = useState(0); // 总价格
  console.log(cid,'cidcidcid');
  
  // 价格
  const price1 = 10; // 第一朵鲜花的价格
  const price2 = 50; // 第二朵鲜花的价格

  const pollIntervalRef = useRef<number | undefined>(undefined);
  const pollTimeoutRef = useRef<number | undefined>(undefined);
  const pollAttemptsRef = useRef<number>(0);
  const MAX_POLLING_ATTEMPTS = 5; // 根据需要调整最大轮询次数
  const user_id = localStorage.getItem("_id");
  // 打开弹出框
  // const handleIconClick = () => {
  //   onClick(true);
  // };

  // 关闭弹出框
  const handleClose = () => {
    setTotalPrice(0); // 重置总票数
    setFlowerCount(0);
    setFlowerCount2(0);
    onClose(false);
  };
  // 生成唯一的 orderId
  const generateOrderId = () => {
    return uuidv4(); // 或者使用更复杂的生成方式
  };

  // 发送支付参数到后端
  const handleSend = async () => {
    if (totalPrice == 0) {
      Toast.fail("票数不能为0");
      return;
    }
    const newOrderId = generateOrderId();
    localStorage.setItem("orderId", newOrderId);
    try {
      const response = await instance.post("/payment/pay", {
        total_fee: totalPrice,
        backendUrl: "https://zcgjcy.com/api/payment/wxnotify",
        buyerId: user_id,
        sellerId: cid,
        order_id: newOrderId,
        title: "支持选手",
      });
      console.log(response);

      if (response.data.errmsg == "success!") {
        window.location.href = `${response.data.url}`;
      } else {
        // Toast.fail("打call失败");
        localStorage.removeItem("orderId"); // 失败时移除 orderId
      }
      setFlowerCount(0); // 重置计数
      onClose(false);
    } catch (error) {
      console.error("打call失败:", error);
      Toast.fail("打call失败");
      localStorage.removeItem("orderId"); // 失败时移除 orderId
    }
  };

  const clearPolling = () => {
    if (pollIntervalRef.current !== undefined) {
      clearInterval(pollIntervalRef.current);
      pollIntervalRef.current = undefined;
    }
    if (pollTimeoutRef.current !== undefined) {
      clearTimeout(pollTimeoutRef.current);
      pollTimeoutRef.current = undefined;
    }
  };

  const checkOrderStatus = async (currentOrderId: string) => {
    try {
      const response = await instance.get("/orderForm/getOrder", {
        params: { orderId: currentOrderId },
      });

      console.log("订单状态:", response.data);

      if (response.data.status === "paid") {
        Toast.success("支付成功！");
        clearPolling();
        localStorage.removeItem("orderId");
        // 可以在此进行其他操作，例如跳转到订单详情页
      } else if (response.data.status === "failed") {
        Toast.fail("支付失败");
        clearPolling();
        localStorage.removeItem("orderId"); // 支付失败后移除 orderId
        // 处理支付失败的逻辑
      } else {
        pollAttemptsRef.current += 1;
        if (pollAttemptsRef.current >= MAX_POLLING_ATTEMPTS) {
          Toast.fail("支付超时，请稍后重试");
          clearPolling();
          localStorage.removeItem("orderId");
        }
        // 如果状态为 'pending' 且未达到最大轮询次数，继续轮询
      }
      // 如果状态为处理中，继续轮询
    } catch (error) {
      console.error("查询订单状态失败:", error);
      // 根据需要处理错误，例如显示提示信息或停止轮询
      clearPolling();
    }
  };

  // 启动轮询
  const startPolling = (currentOrderId: string) => {
    if (
      pollIntervalRef.current !== undefined ||
      pollTimeoutRef.current !== undefined
    )
      return; // 防止多个定时器

    // 延迟1秒开始轮询
    pollTimeoutRef.current = window.setTimeout(() => {
      const intervalId = window.setInterval(() => {
        checkOrderStatus(currentOrderId);
      }, 500); // 每1秒查询一次
      pollIntervalRef.current = intervalId;
    }, 1000); // 延迟1秒开始
  };

  // 在组件挂载时检测是否有未完成的订单
  useEffect(() => {
    const existingOrderId = localStorage.getItem("orderId");
    if (existingOrderId) {
      startPolling(existingOrderId);
    }

    // 清理定时器，防止内存泄漏
    return () => {
      clearPolling();
      localStorage.removeItem("orderId");
    };
  }, []);

  // 处理点击第一朵鲜花
  const handleAddFlower = () => {
    setFlowerCount(flowerCount + 1);
    setTotalPrice(totalPrice + price1);
  };

  // 处理点击第二朵鲜花
  const handleAddFlower2 = () => {
    setFlowerCount2(flowerCount2 + 1);
    setTotalPrice(totalPrice + price2);
  };

  const [isClicked, setIsClicked] = useState(false);
  const [isClicked2, setIsClicked2] = useState(false);

  const handleImageClick = () => {
    setIsClicked(!isClicked);

    // 如果想要动画播放后恢复，可以设置一个短暂的定时器来重置状态
    setTimeout(() => {
      setIsClicked(false);
    }, 300); // 与CSS中的transition时间相匹配
  };

  const ComputeTotalPrice = (price:any) => {
    setTotalPrice(price);
    setFlowerCount(0);
    setFlowerCount2(0);
  };

  const handleImageClick2 = () => {
    setIsClicked2(!isClicked2);

    // 如果想要动画播放后恢复，可以设置一个短暂的定时器来重置状态
    setTimeout(() => {
      setIsClicked2(false);
    }, 300); // 与CSS中的transition时间相匹配
  };
  return (
      
        <div  className = {style.popup}>
          <div  className = {style.popupContent}>
            <h2>点击鲜花增加数量哦~</h2>
            <div
              style={{
                cursor: "pointer",
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
              }}
            >
              <div style={{ textAlign: "center", marginRight: "10%" }}>
                <Badge content={flowerCount} color="red">
                  <img
                    src={flower} // 替换为鲜花图标URL
                    alt="Flower Icon 1"
                    style={{ width: "100px", height: "100px", margin: 0 }}
                    className={`${style.accumulatedNum}  ${isClicked ? style.clicked : ""}`}
                    onClick={() => {
                      handleImageClick();
                      handleAddFlower();
                    }}
                  />
                </Badge>
                <p style={{ margin: 0 }}>{price1}票</p>
              </div>
              <div style={{ textAlign: "center" }}>
                <Badge content={flowerCount2} color="red">
                  <img
                    src={flower1} // 替换为鲜花图标URL
                    alt="Flower Icon 2"
                    style={{ width: "100px", height: "100px", margin: 0 }}
                    className={`${style.accumulatedNum}  ${isClicked ? style.clicked : ""}`}
                    onClick={() => {
                      handleImageClick2();
                      handleAddFlower2();
                    }}
                  />
                </Badge>
                <p style={{ margin: 0 }}>{price2}票</p>
              </div>
            </div>
            <input
              type="number"
              style={{ paddingLeft: "2ch", paddingRight: "2ch" }}
              className={style.inputTotal}
              value={totalPrice > 0 ? totalPrice : NaN}
              onChange={(event) =>
                ComputeTotalPrice(Number(event.target.value))
              }
              placeholder="也可以直接输入票数哦~"
            />
            <p style={{marginTop:'5px',marginBottom:'5px'}}>总票数：{totalPrice}票</p>
            <div className={style.buttonContainer}>
              <button onClick={handleClose}>取消</button>
              <button onClick={handleSend}>送出</button>
            </div>
          </div>
        </div>
  );
};

export default SupportContestant;
